import React, { useRef, useState } from 'react';
import { useQueryClient, useMutation } from 'react-query';
import MarkdownEditor from "@/components/markdown-editor";
import MarkdownPreviewer from "@/components/markdown-previewer";
import { updateQuestionById, createQuestionByExerciseId } from "@/apis/exercise";

/**
 * It seems that The QuestionEditor and QuestionMaker componsnet is similar.
 * This Time I don't konwn how to split them.
 */

function QuestionEditor({ question, isUpdating, setIsUpdating, setIsCreating, exerciseId, courseId }) {
    const queryClient = useQueryClient();

    const categoryRef = useRef();
    const scoreRef = useRef();

    const [newContent, setNewContent] = useState(isUpdating && question && question.content);
    const [newAnswer, setNewAnswer] = useState(isUpdating && question && question.answer);

    const mutateQuestion = useMutation(updateQuestionById, {
        onSuccess: () => {
            queryClient.invalidateQueries(['questions', exerciseId]);
        },
    });

    const createQuestion = useMutation(createQuestionByExerciseId, {
        onSuccess: () => {
            queryClient.invalidateQueries(['questions', exerciseId]);
        },
    });

    function handleSave(e) {
        e.preventDefault();
        if (isUpdating) {
            mutateQuestion.mutate({
                newContent,
                newAnswer,
                newCategory: categoryRef.current.value,
                newScore: scoreRef.current.value,
                questionId: question && question.id,
                courseId,
            });
        }
        else {
            createQuestion.mutate({
                newContent,
                newAnswer,
                newCategory: categoryRef.current.value,
                newScore: scoreRef.current.value,
                exerciseId,
                courseId,
            })
        }
        setIsUpdating(false);
        setIsCreating(false);
    }

    return (
        <div className="card">
            <div className="card-body">
                <label className="pb-3">请输入题干:</label>
                <MarkdownEditor initialMarkdown={newContent} setMarkdown={setNewContent} Id={`newContent-${question && question.id}`} width={'100%'} />
                <label className="py-3">请输入答案:</label>
                <MarkdownEditor initialMarkdown={newAnswer} setMarkdown={setNewAnswer} Id={`newAnswer-${question && question.id}`} width={'100%'} />
                <label className="py-3">输入题目类型:</label>
                <select class="form-select" aria-label="选择题目类型" ref={categoryRef}>
                    <option value="0" selected>简答题</option>
                    <option value="1">单选题</option>
                </select>
                <label className="py-3 me-3">分值(0-100):</label>
                <input type="number" min="0" max="100" value={question && question.score} ref={scoreRef}></input>
                <div>
                    <button className="btn btn-outline-primary" onClick={handleSave}>保存题目</button>
                </div>
            </div>
        </div>
    )
}

function QuestionMaker({ question, exerciseId, courseId }) {
    const queryClient = useQueryClient();

    const categoryRef = useRef();
    const scoreRef = useRef();

    const [isCreating, setIsCreating] = useState(false);
    const [newContent, setNewContent] = useState(question && question.content);
    const [newAnswer, setNewAnswer] = useState(question && question.answer);

    const createQuestion = useMutation(createQuestionByExerciseId, {
        onSuccess: () => {
            queryClient.invalidateQueries(['questions', exerciseId]);
        },
    });

    function handleSave(e) {
        e.preventDefault();
        createQuestion.mutate({
            newContent,
            newAnswer,
            newCategory: categoryRef.current.value,
            newScore: scoreRef.current.value,
            exerciseId,
            courseId,
        })
        setIsCreating(false);
    }

    function handleCreate(e) {
        e.preventDefault();
        setIsCreating(true);
    }

    return (
        <div>
            {!isCreating &&
                <div className="d-flex">
                    <button className="btn btn-outline-primary ms-auto" onClick={handleCreate}>添加题目</button>
                </div>
            }
            {isCreating &&
                <div className="card">

                    <div className="card-body">
                        <label className="pb-3">请输入题干:</label>
                        <MarkdownEditor initialMarkdown={newContent} setMarkdown={setNewContent} Id={`newContent-${question && question.id}`} width={'100%'} />
                        <label className="py-3">请输入答案:</label>
                        <MarkdownEditor initialMarkdown={newAnswer} setMarkdown={setNewAnswer} Id={`newAnswer-${question && question.id}`} width={'100%'} />
                        <label className="py-3">输入题目类型:</label>
                        <select class="form-select" aria-label="选择题目类型" ref={categoryRef}>
                            <option value="0" selected>简答题</option>
                            <option value="1">单选题</option>
                        </select>
                        <label className="py-3 me-3">分值(0-100):</label>
                        <input type="number" min="0" max="100" value={question && question.score} ref={scoreRef}></input>
                        <div>
                            <button className="btn btn-outline-primary" onClick={handleSave}>保存题目</button>
                        </div>
                    </div>
                </div>
            }
        </div>
    )
}

function QuestionItem({ question, isSubmitted, exerciseId, isCourseManager, courseId }) {

    const [isUpdating, setIsUpdating] = useState(false);
    const [isCreating, setIsCreating] = useState(false);
    const [isAnswering, setIsAnswering] = useState(false);
    const [isAnswered, setIsAnswered] = useState(false);
    const [answer, setAnswer] = useState('');

    function handleUpdate(e) {
        e.preventDefault();
        setIsUpdating(true);
    }

    function handleCreate(e) {
        e.preventDefault();
        setIsCreating(true);
    }

    function handleAnswer(e) {
        e.preventDefault();
        setIsAnswering(true);
    }

    return (
        <li>
            {!isUpdating &&
                <div className="card border-light">
                    <div className="card-body">
                        <MarkdownPreviewer markdown={question && (question.content + '&nbsp;&#40;' + question.score + '&#39;&#41;')} id={`question-previewer-${question && question.id}`} />
                        <div className='py-1'></div>
                        {(!isAnswered && !isAnswering) &&
                            <button className="btn btn-outline-secondary my-2" onClick={handleAnswer}>写回答</button>
                        }
                        {(isAnswering && !isAnswered) &&
                            <MarkdownEditor initialMarkdown={answer} setMarkdown={setAnswer} Id={`answer-${question && question.id}`} width={'100%'} setBlur={setIsAnswered} />
                        }
                        {isAnswered &&
                            <div className="card mb-1">
                                <div className="card-header">我的答案</div>
                                <div className="card-body">
                                    <MarkdownPreviewer markdown={answer} id={`answer-previwer-${question && question.id}`} />
                                </div>
                            </div>
                        }
                        {isSubmitted &&
                            <div className="card">
                                <div className="card-header text-danger">解析</div>
                                <div className="card-body">
                                    <MarkdownPreviewer markdown={question && question.answer} id={`check-answer-previwer-${question && question.id}`} />
                                </div>
                            </div>
                        }
                        {isCourseManager &&
                            <div className="mt-2">
                                <button className="btn btn-outline-primary me-2" onClick={handleUpdate}>修改题目</button>
                                <button className="btn btn-outline-primary" onClick={handleCreate}>添加题目</button>
                            </div>
                        }
                    </div>
                </div>
            }

            {(isUpdating || isCreating) &&
                <QuestionEditor courseId={courseId} question={question} isUpdating={isUpdating} exerciseId={exerciseId} setIsUpdating={setIsUpdating} setIsCreating={setIsCreating} />
            }
        </li>
    )
};

export default function QuestionList({ questions, exerciseId, isCourseManager, courseId }) {

    const [isSubmitted, setIsSubmitted] = useState(false);

    function handleSubmit(e) {
        setIsSubmitted(!isSubmitted);
    }

    const questionsArray = questions || [];
    const questionItems = questionsArray.map((question) => (
        <QuestionItem key={question && question.id} question={question} isSubmitted={isSubmitted} exerciseId={exerciseId} isCourseManager={isCourseManager} courseId={courseId} />
    ));

    return (
        <div>
            {isCourseManager &&
                <QuestionMaker question={null} exerciseId={exerciseId} courseId={courseId} />
            }
            <ol>
                {questionItems}
            </ol>
            {questionsArray.length > 0 &&
                <div className="row justify-content-center">
                    <button className="btn btn-outline-secondary col-2" onClick={handleSubmit}>对照答案</button>
                </div>
            }
        </div>
    )
}